import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useStoreStore = defineStore('store', () => {
  const STORE_KEY = 'erppos_stores'
  const REG_KEY = 'erppos_registers'
  const stores = ref([])
  const registers = ref([])

  const initialize = () => {
    const s = localStorage.getItem(STORE_KEY)
    const r = localStorage.getItem(REG_KEY)
    if (s) stores.value = JSON.parse(s)
    if (r) registers.value = JSON.parse(r)
    if (s) return
    stores.value = [
      { id: 'ST001', name: '旗舰店', code: 'HQ', city: '上海', address: '黄浦区XX路', openTime: '10:00', closeTime: '22:00', status: 'open' },
      { id: 'ST002', name: '天河店', code: 'TH', city: '广州', address: '天河区XX路', openTime: '10:00', closeTime: '22:00', status: 'open' },
    ]
    registers.value = [
      { id: 'R001', name: '前台1号机', storeId: 'ST001', sn: 'POS-001', channel: '线下', status: 'enabled' },
      { id: 'R002', name: '前台2号机', storeId: 'ST001', sn: 'POS-002', channel: '线下', status: 'enabled' },
      { id: 'R003', name: '云小店终端', storeId: 'ST002', sn: 'POS-101', channel: '小程序', status: 'disabled' },
    ]
    persist()
  }

  const persist = () => {
    localStorage.setItem(STORE_KEY, JSON.stringify(stores.value))
    localStorage.setItem(REG_KEY, JSON.stringify(registers.value))
  }

  // 门店 CRUD
  const addStore = (data) => { const v = { id: 'ST' + Date.now(), status: 'open', ...data }; stores.value.unshift(v); persist(); return v }
  const updateStore = (id, data) => { const i = stores.value.findIndex(x=>x.id===id); if(i>-1){ stores.value[i] = { ...stores.value[i], ...data }; persist(); return stores.value[i] } return null }
  const removeStore = (id) => { const i = stores.value.findIndex(x=>x.id===id); if(i>-1){ stores.value.splice(i,1); persist(); return true } return false }

  // 收银点 CRUD
  const addRegister = (data) => { const v = { id: 'R' + Date.now(), status: 'enabled', ...data }; registers.value.unshift(v); persist(); return v }
  const updateRegister = (id, data) => { const i = registers.value.findIndex(x=>x.id===id); if(i>-1){ registers.value[i] = { ...registers.value[i], ...data }; persist(); return registers.value[i] } return null }
  const removeRegister = (id) => { const i = registers.value.findIndex(x=>x.id===id); if(i>-1){ registers.value.splice(i,1); persist(); return true } return false }

  const getRegistersByStore = (storeId) => registers.value.filter(x=>x.storeId===storeId)
  const totalStores = computed(()=>stores.value.length)
  const totalRegisters = computed(()=>registers.value.length)

  return {
    stores, registers,
    initialize, persist,
    addStore, updateStore, removeStore,
    addRegister, updateRegister, removeRegister,
    getRegistersByStore,
    totalStores, totalRegisters,
  }
})


